"""
FileName：pytest_with_poll.py
Description：
Author：gaojiahui
Time：2025/8/16 15:18
Website：https://gitee.com/gao-jiahui
"""
import requests
import requests_mock

from day03_db.test_auto_db import db_validator
from day03_mock.test_mock_payment_flow import create_test_order, mock_payment
from day03_poll.test_03_poll_controller import PollingController


"""集成到Pytest测试"""

def test_payment_timeout(create_test_order,mock_payment,db_validator):
    """测试支付超时场景"""
    order_id = create_test_order()
    payment = mock_payment(order_id)

    # 设置Mock永不回调
    with requests_mock.Mocker() as m:
        m.post(payment["callback_url"], status_code=200)
        requests.get(payment["pay_url"])

    # 轮询控制器
    controller = PollingController(timeout=20,interval=3)
    result = controller.poll(
        lambda : get_order_status(order_id)  == "PAID"
    )

    assert result["staus"] == "timeout"
    assert result["duration"] >= 20

    # 验证订单状态
    db_order = db_validator.get_order_by_id(order_id)
    assert db_order["status"] == "PENDING"

    # 验证超时处理
    cancel_response = requests.post(
        f"/order/{order_id}/cancel",
        json={"reason":"支付超时"}
    )
    assert cancel_response.status_code == 200
    assert db_validator.get_order_status == "CANCELLED"